import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/album_service.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/event/upload_photo_event.dart';
import 'package:flutter_oldman_health/models/album_data_model.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/pages/album/album_page.dart';
import 'package:flutter_oldman_health/pages/album/photo_view_page.dart';
import 'package:flutter_oldman_health/utils/event_bus.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';
import 'package:flutter_oldman_health/widget/edit_dialog.dart';
import 'package:flutter_oldman_health/widget/uploading_photos.dart';
import "package:images_picker/images_picker.dart";

class AlbumItemPage extends StatefulWidget {
  AlbumModel album;
  AlbumPage albumPageWidget;
  List<String> albumAllListName;

  AlbumItemPage(this.album, this.albumPageWidget, this.albumAllListName);

  @override
  _AlbumItemPageState createState() {
    return _AlbumItemPageState();
  }
}

class _AlbumItemPageState extends State<AlbumItemPage> {
  List<PhotoModel> photoList = [];
  List<PhotoModel> checkedPhotoList = [];
  Size screenSize;

  bool isLoadingData = false;
  bool upLoadingData = false;
  bool deleteStatus = false;
  bool isDeletingeData = false;
  int needRefresh = -1;

  @override
  void initState() {
    super.initState();
    queryAlbumList(widget.album.name);

    EventBus().on("UploadCallbackEvent", (event) {
      print("eventbus UploadCallbackEvent ");
      if (!event) queryAlbumList(widget.album.name);
      setState(() {
        upLoadingData = event;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    EventBus().off("UploadCallbackEvent");
  }

  Future _getImage() async {
    List<Media> res = await ImagesPicker.pick(
      count: 9,
      language: Language.Chinese,
      pickType: PickType.image,
    );
    res.forEach((element) {
      print("_getImagePath : " + element.path);
    });
    EventBus()
        .emit("UploadPhotosEvent", UploadPhotosEvent(widget.album.id, res));
  }

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;
    Future<void> _handleRefresh() async {
      bool load = await queryAlbumList(widget.album.name);
      if (load) {
        EasyLoading.showSuccess('已刷新');
      }
    }

    return MaterialApp(
        home: Scaffold(
            body: WillPopScope(
                onWillPop: () async {
                  Navigator.pop(context, needRefresh);
                  return false;
                },
                child: Container(
                    color: Constant.backgroundColor,
                    alignment: Alignment.center,
                    child: Column(children: [
                      _getTitle(widget.album.name),
                      if (upLoadingData) CommonContainer.uploadingView(),
                      Expanded(
                          flex: 1,
                          child: Stack(children: [
                            isLoadingData
                                ? CommonContainer.loadingView()
                                : photoList.isEmpty
                                    ? showListEmpty()
                                    : Container(
                                        padding: EdgeInsets.only(
                                            left: (deleteStatus) ? 16 : 0),
                                        alignment: Alignment.center,
                                        width: screenSize.width - 26,
                                        height: screenSize.height - 118,
                                        child: RefreshIndicator(
                                            onRefresh: _handleRefresh,
                                            color: Color(0xaa0D47A1),
                                            backgroundColor: Colors.black38,
                                            child: _getGridView())),
                            if (deleteStatus && photoList.isNotEmpty)
                              deleteMenuWidget(),
                            if (isDeletingeData) CommonContainer.loadingView()
                          ]))
                    ])))));
  }

  List<Widget> _getListData() {
    var tempList = photoList.map((e) => Card(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadiusDirectional.circular(8)),
        clipBehavior: Clip.antiAlias,
        child: _getImageWidget(e)));
    return tempList.toList();
  }

  Widget _getGridView() {
    return MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: GridView(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              childAspectRatio: 1,
              crossAxisCount: 3,
              mainAxisSpacing: 4,
              crossAxisSpacing: 4,
            ),
            children: _getListData()));
  }

  Widget _getImageWidget(PhotoModel img) {
    return img.location != null
        ? GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () async {
              if (deleteStatus) {
                if (checkedPhotoList.contains(img)) {
                  setState(() {
                    checkedPhotoList.remove(img);
                  });
                } else {
                  setState(() {
                    checkedPhotoList.add(img);
                  });
                }
              } else {
                int refresh = await Navigator.push(context,
                    MaterialPageRoute(builder: (context) {
                  return PhotoViewPage(photoList, img, widget.album.creator);
                }));
                if (null != refresh && refresh > 0) {
                  queryAlbumList(widget.album.name);
                }
              }
            },
            child: Stack(alignment: Alignment.bottomCenter, children: [
              Container(
                  child: CachedNetworkImage(
                    width: double.maxFinite,
                    height: screenSize.width / 2 - 20,
                    fit: BoxFit.cover,
                    imageUrl: img.location,
                    placeholder: (context, url) => assetImage(),
                    // CommonContainer.loadingView(h: 50),
                    errorWidget: (context, url, error) => assetImage(),
                  ),
                  alignment: Alignment.center),
              if (checkedPhotoList.contains(img))
                Container(
                    height: 30,
                    width: double.maxFinite,
                    color: Colors.orange,
                    child:
                        Icon(Icons.check_sharp, size: 25, color: Colors.white))
            ]))
        : assetImage();
  }

  Widget assetImage() {
    return Image.asset('images/ic_album.png',
        width: double.maxFinite,
        height: screenSize.width / 2 - 20,
        fit: BoxFit.cover);
  }

  Widget showListEmpty() {
    return Align(
        alignment: Alignment.center,
        child: Column(children: [
          Padding(
            padding: EdgeInsets.only(top: 48),
            child: Image.asset('images/ic_album.png'),
          ),
          Padding(
            padding: EdgeInsets.only(top: 8, bottom: 16),
            child: Text("空空如也，请先上传照片", style: TextStyle(fontSize: 18)),
          ),
          if (widget.album.myAlbum())
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                _getImage();
                // showAlbumOperation();
              },
              child: Container(
                  width: screenSize.width - 32,
                  margin: EdgeInsets.all(16),
                  padding: EdgeInsets.fromLTRB(16, 12, 16, 12),
                  alignment: Alignment.center,
                  child: Text("上传照片",
                      style: TextStyle(color: Colors.white, fontSize: 18)),
                  decoration: BoxDecoration(
                      color: Colors.orange,
                      borderRadius: BorderRadius.all(Radius.circular(18)))),
            )
        ]));
  }

  Future<bool> queryAlbumList(String albumName) async {
    checkedPhotoList.clear();
    setState(() {
      upLoadingData = UploadingPhotos.upLoading;
      isLoadingData = true;
    });
    AlbumService.queryAlbumList(name: albumName).then((value) {
      setState(() {
        isLoadingData = false;
      });
      if (value != null && value.statusCode == 200) {
        AlbumDataModel albumDataModel = AlbumDataModel.fromJson(value.data);
        if (albumDataModel != null &&
            albumDataModel.success() &&
            albumDataModel.data != null) {
          if (albumDataModel.data.isNotEmpty) {
            if (albumDataModel.data.length > 1) {
              albumDataModel.data.forEach((element) {
                if (element.creator == widget.album.creator) {
                  setState(() {
                    photoList = element.photos;
                  });
                }
              });
            } else {
              setState(() {
                photoList = albumDataModel.data[0].photos;
              });
            }
          }
        } else {
          EasyLoading.showInfo(albumDataModel.msg);
        }
      }
      return null != value && value.statusCode == 200;
    });
    return true;
  }

  Widget deleteMenuWidget() {
    return Align(
        alignment: Alignment.bottomCenter,
        child: Container(
            width: screenSize.width,
            padding: EdgeInsets.only(right: 16),
            color: Colors.white70,
            child: Row(children: [
              GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  child: Container(
                      padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
                      child: Text("取消", style: TextStyle(fontSize: 18))),
                  onTap: () {
                    setState(() {
                      deleteStatus = false;
                      checkedPhotoList.clear();
                    });
                  }),
              Expanded(
                  flex: 1,
                  child: Padding(padding: EdgeInsets.fromLTRB(16, 16, 16, 16))),
              // Radio(
              //     activeColor: Colors.orangeAccent,
              //     groupValue: checkedPhotoList.length,
              //     value: photoList.length,
              //     onChanged: (check) {
              //       setState(() {
              //         checkAllSelect(check);
              //       });
              //     }),
              GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  child: Container(
                      margin: EdgeInsets.only(right: 12),
                      padding: EdgeInsets.fromLTRB(0, 12, 16, 12),
                      child: Text(
                          checkedPhotoList.length == photoList.length
                              ? "取消全选"
                              : "全选",
                          style: TextStyle(fontSize: 18))),
                  onTap: () {
                    checkAllSelect(checkedPhotoList.length == photoList.length);
                  }),
              ElevatedButton(
                  onPressed: () async {
                    if (checkedPhotoList.isNotEmpty) {
                      setState(() {
                        isDeletingeData = true;
                      });
                      checkedPhotoList.forEach((e) {
                        AlbumService.deletePhoto(e.id).then((value) {
                          if (value != null && value.statusCode == 200) {
                            needRefresh = 1;
                            ResponseDataModel data =
                                ResponseDataModel.fromJson(value.data);
                            if (data != null && data.success()) {
                              setState(() {
                                deleteStatus = false;
                                photoList.remove(e);
                              });
                            } else {
                              EasyLoading.showInfo(data.msg);
                            }
                          }
                        }).whenComplete(() {
                          if (e == checkedPhotoList.last) {
                            setState(() {
                              isDeletingeData = false;
                              checkedPhotoList.clear();
                            });
                          }
                        });
                      });
                    }
                  },
                  child: Padding(
                      padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
                      child: Text("删除")),
                  style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(Colors.orange),
                      textStyle:
                          MaterialStateProperty.all(TextStyle(fontSize: 17)),
                      shape: MaterialStateProperty.all(StadiumBorder(
                          side: BorderSide(
                        //设置 界面效果 圆角弧度
                        style: BorderStyle.solid,
                        color: Color(0xffFF7F24),
                      ))))),
            ])));
  }

  checkAllSelect(bool equalLength) {
    if (equalLength) {
      setState(() {
        checkedPhotoList.clear();
      });
    } else {
      checkedPhotoList.clear();
      photoList.forEach((element) {
        if (checkedPhotoList.length == photoList.length - 1) {
          setState(() {
            checkedPhotoList.add(element);
          });
        } else {
          checkedPhotoList.add(element);
        }
      });
    }
  }

  Widget _getTitle([String title = "相册"]) {
    return Container(
        color: Constant.appbarColor,
        padding: EdgeInsets.fromLTRB(28, 46, 28, 16),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                left: 2,
                child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    Navigator.pop(context, needRefresh);
                  },
                  child: Container(
                      child: Icon(Icons.arrow_back_ios),
                      padding: EdgeInsets.fromLTRB(10, 10, 20, 10)),
                ),
              ),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal)),
              if (widget.album.myAlbum() && !deleteStatus)
                Positioned(
                    right: 2,
                    child: GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTap: () {
                          showAlbumOperation();
                        },
                        child: Icon(Icons.more_horiz_sharp, size: 28)))
            ],
          ),
        ));
  }

  showAlbumOperation() async {
    showDialog(
        context: context,
        builder: (context) {
          return SimpleDialog(children: [
            GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async {
                  _getImage();
                  Navigator.pop(context);
                },
                child: Container(
                    padding: EdgeInsets.all(12),
                    alignment: Alignment.center,
                    child: Text("添加图片", style: TextStyle(fontSize: 17)))),
            Divider(height: 1, indent: 16, endIndent: 16),
            GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async {
                  Navigator.pop(context);

                  List<Media> res =
                      await ImagesPicker.openCamera(pickType: PickType.image);

                  EventBus().emit("UploadPhotosEvent",
                      UploadPhotosEvent(widget.album.id, res));
                },
                child: Container(
                    padding: EdgeInsets.all(12),
                    width: screenSize.width - 16,
                    alignment: Alignment.center,
                    child: Text("拍照", style: TextStyle(fontSize: 17)))),
            if (null != photoList && photoList.length > 0)
              Divider(height: 1, indent: 16, endIndent: 16),
            if (null != photoList && photoList.length > 0)
              GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    setState(() {
                      deleteStatus = !deleteStatus;
                    });
                    Navigator.pop(context);
                  },
                  child: Container(
                      padding: EdgeInsets.all(12),
                      alignment: Alignment.center,
                      child: Text("删除图片",
                          style: TextStyle(color: Colors.red, fontSize: 17)))),
            Divider(height: 1, indent: 16, endIndent: 16),
            GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async {
                  Navigator.pop(context);

                  String newAlbumName = await showDialog(
                      context: context,
                      builder: (context) => CustomEditDialog(
                          "修改相册", widget.album.name,
                          type: 1, allListName: widget.albumAllListName));

                  if (null != newAlbumName &&
                      newAlbumName != widget.album.name) {
                    AlbumService.updateAlbum(newAlbumName, widget.album.id)
                        .then((value) {
                      if (null != value && value.statusCode == 200) {
                        needRefresh = 1;
                        setState(() {
                          widget.album.name = newAlbumName;
                        });
                      }
                    });
                  }
                },
                child: Container(
                    padding: EdgeInsets.all(12),
                    alignment: Alignment.center,
                    child: Text("修改相册", style: TextStyle(fontSize: 17)))),
            Divider(height: 1, indent: 16, endIndent: 16),
            Container(
                margin: EdgeInsets.fromLTRB(12, 8, 12, 0),
                child: ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                        padding: EdgeInsets.all(10), child: Text("取消")),
                    style: ButtonStyle(
                        shape: MaterialStateProperty.all(StadiumBorder(
                            side: BorderSide(
                                //设置 界面效果 圆角弧度
                                style: BorderStyle.none,
                                color: Colors.orange))),
                        backgroundColor:
                            MaterialStateProperty.all(Colors.orange),
                        textStyle: MaterialStateProperty.all(
                            TextStyle(fontSize: 17)))))
          ]);
        });
  }
}
